<?php
/**
 * @title 110. 平衡二叉树 - 递归
 * @author start2004
 */

// ini_set("memory_limit", "128M");


class Solution {

    /**
     * @param TreeNode $root
     * @return Boolean
     */
    function isBalanced($root) {
        /**
         * @since 2020-08-17 二叉树的深度
         */
        // echo "left=", self::find($root->left), PHP_EOL;
        // echo "right=", self::find($root->right), PHP_EOL;
        $depth = self::find($root);

        /**
         * @since 2020-08-17 是否平衡二叉树
         */
        if($depth !== false){
            $depth = true;
        } else {}

        /**
         * @return
         */
        return $depth;
    }


    /**
     * @title 树的深度
     * @author start2004
     * @since 2020-08-17 Created
     *
     * @param $root
     */
    public function find($root){
        if($root === null){
            return 0;
        } else {}

        /**
         * @since 2020-08-17 左子树
         */
        if($root->left !== null){
            $leftDepth = self::find($root->left);
            if($leftDepth === false){
                return false;
            } else {
                $leftDepth++;
            }
        } else {
            $leftDepth = 0;
        }

        /**
         * @since 2020-08-17 右子树
         */
        if($root->right !== null){
            $rightDepth = self::find($root->right);
            if($rightDepth === false){
                return false;
            } else {
                $rightDepth++;
            }
        } else {
            $rightDepth = 0;
        }

        /**
         * @since 2020-08-17 高度差
         */
        if(abs($leftDepth-$rightDepth) <=1){
            return max($leftDepth, $rightDepth);
        } else {
            return false;
        }
    }
}


/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.17.php
 */
$datas = [
    // [3,9,20,null,null,15,7],
    // [1,2,2,3,3,null,null,4,4],
    [1,2,2,3,null,null,3,4,null,null,4],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->isBalanced($xhprof->tree($data));
    var_dump($result);
    // if(count($result)<=20){
    //     var_dump($result);
    // } else {
    //     var_dump(count($result));
    // }
    echo str_repeat("<br>", 3);
}
$xhprof->end();
